package com.develope.tree;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.ksoap2.serialization.PropertyInfo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.develope.tree.db.DBHelper;
import com.develope.tree.db.dbUserParcel;
import com.develope.tree.image.ManagerPicture;
import com.develope.tree.service.HttpHandler;
import com.develope.tree.service.MyService;
import com.develope.tree.service.SoapHelper;
import com.develope.tree.utils.Alerts;
import com.develope.tree.utils.Utils;


@SuppressLint("SimpleDateFormat")
public class MainActivity extends Activity implements OnClickListener {
	public final static String PAR = "com.develope.tree.PAR";
	static final int REQUEST_IMAGE_CAPTURE = 1;
	private ImageView mImageView;

	private Button btnSave;
	private EditText user;
	private Spinner lo;
	private EditText cay;
	private EditText dates;
	private RadioGroup rdbGrTinh_trang;
	private RadioGroup rdbGrKthuoc_ho;
	private RadioGroup rdbGrCo_dinh;
	private RadioGroup rdbGrBong_che;
	private EditText chCao;
	private EditText chVi;
	private RadioGroup rdbGrTia_canh;
	private RadioGroup rdbGrLam_co;
	private RadioGroup rdbGrDo_am;
	private EditText time_bon;
	private EditText luong_bon;
	private EditText time_phun;
	private EditText luong_phun;
	private EditText sluong_cay;
	private EditText sluong_luong;
	private RadioGroup rdbGrDgia_chung;
	private EditText vd_khac;
	private CheckBox chk_bt, chk_chm, chk_vla, chk_bla, chk_dlo, chk_xla,
			chk_bthung, chk_khac;
	private CheckBox chk_tThu, chk_phy, chk_rSap, chk_rVang, chk_chau,
			chk_skhac;

	DBHelper mydb;
	dbUserParcel userdb;
	LocationListener locationlistener;

	Calendar cal;

	private MyService s;
	private ArrayList<UserParcel> arrUser, arrParcel;
	private ArrayList<String> arrLo =new ArrayList<String>();
	private ArrayAdapter<String> adapterLo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Intent i = getIntent();
		String mUser = i.getStringExtra(com.develope.tree.login.LoginActivity.EXTRA_MESSAGE);
		user = (EditText) findViewById(R.id.e_user);
		cay = (EditText) findViewById(R.id.e_cay);
		chCao = (EditText) findViewById(R.id.e_cao);
		chVi = (EditText) findViewById(R.id.e_cv);
		time_bon = (EditText) findViewById(R.id.e_bon);
		luong_bon = (EditText) findViewById(R.id.e_lphan);
		time_phun = (EditText) findViewById(R.id.e_phun);
		luong_phun = (EditText) findViewById(R.id.e_lthuoc);
		sluong_cay = (EditText) findViewById(R.id.e_trencay);
		sluong_luong = (EditText) findViewById(R.id.e_trenluong);
		vd_khac = (EditText) findViewById(R.id.e_vde);

		rdbGrTinh_trang = (RadioGroup) findViewById(R.id.rdbGr);
		rdbGrKthuoc_ho = (RadioGroup) findViewById(R.id.rdbGr1);
		rdbGrCo_dinh = (RadioGroup) findViewById(R.id.rdbGr2);
		rdbGrBong_che = (RadioGroup) findViewById(R.id.rdbGr3);
		rdbGrTia_canh = (RadioGroup) findViewById(R.id.rdbGr4);
		rdbGrLam_co = (RadioGroup) findViewById(R.id.rdbGr5);
		rdbGrDo_am = (RadioGroup) findViewById(R.id.rdbGr7);
		rdbGrDgia_chung = (RadioGroup) findViewById(R.id.rdbGr8);

		chk_bt = (CheckBox) findViewById(R.id.chk_bt);
		chk_chm = (CheckBox) findViewById(R.id.chk_chm);
		chk_vla = (CheckBox) findViewById(R.id.chk_vla);
		chk_bla = (CheckBox) findViewById(R.id.chk_bla);
		chk_dlo = (CheckBox) findViewById(R.id.chk_ducLo);
		chk_xla = (CheckBox) findViewById(R.id.chk_xla);
		chk_bthung = (CheckBox) findViewById(R.id.chk_biThung);
		chk_khac = (CheckBox) findViewById(R.id.chk_khac);

		chk_tThu = (CheckBox) findViewById(R.id.chk_tThu);
		chk_phy = (CheckBox) findViewById(R.id.chk_phy);
		chk_rSap = (CheckBox) findViewById(R.id.chk_rSap);
		chk_rVang = (CheckBox) findViewById(R.id.chk_rVang);
		chk_chau = (CheckBox) findViewById(R.id.chk_chau);
		chk_skhac = (CheckBox) findViewById(R.id.chk_skhac);

		Button btnDate = (Button) findViewById(R.id.bt_date);
		btnSave = (Button) findViewById(R.id.bt_save);
		
		Button btnPreview = (Button) findViewById(R.id.bt_preview);
		
		btnDate.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		btnPreview.setOnClickListener(this);

		mydb = new DBHelper(this);
		mydb.getWritableDatabase();
		userdb = new dbUserParcel(this);
		userdb.getWritableDatabase();

		
		arrParcel = new ArrayList<UserParcel>();
		arrParcel = null;
		arrLo.add("SELECT PARCEL");
		arrParcel =userdb.getAllParcel(mUser);		
		for (int j = 0; j < arrParcel.size(); j++){
			UserParcel up = new UserParcel();
			up = arrParcel.get(j);
			arrLo.add(up.getParcelName());
			
		}
		
		lo = (Spinner) findViewById(R.id.spinner1);
		adapterLo = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, arrLo);
		adapterLo.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		lo.setAdapter(adapterLo);
		lo.setSelection(0);
		lo.setOnItemSelectedListener(new MyProcessEvent());

		// Date (luc nay chua assign dates da su dung
		dates = (EditText) findViewById(R.id.e_date);
		cal = Calendar.getInstance();
		// viet utils convert date to string de dung o nhieu noi
		// neu dung format string khac thi dung method dateToString(date,
		// formatstring)
		dates.setText(Utils.dateToStringDDMMYYYY(cal.getTime()));

		// check location dung utils de goi duoc o nhieu activity khac
		Utils.isLocationServiceEnabled(this, false);
		
		user.setText(mUser);
		
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		if(extras != null){
		String message = intent.getStringExtra(com.develope.tree.ManagerTree.EXTRA_MESSAGE1);
			cay.setText(message);
			cay.requestFocus();
			chCao.setText(message);
			chVi.setText(message);
		}
		
	}

	@Override
	protected void onResume() {
		super.onResume();
		Intent intent = new Intent(this, MyService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unbindService(mConnection);
	}

	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName className) {
			// TODO Auto-generated method stub
			s = null;

		}

		@Override
		public void onServiceConnected(ComponentName className, IBinder binder) {
			// TODO Auto-generated method stub

			MyService.MyBinder b = (MyService.MyBinder) binder;
			s = b.getService();
			BaseApplication.makeToastMsg("Connected");
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {		
		case R.id.Manager_data:
			Intent intent = new Intent(this, ManagerTree.class);
			startActivity(intent);
			return true;
		case R.id.Manager_image:
			managerImage();
			
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub

		switch (view.getId()) {

		case R.id.bt_save:
//			insertTree();
			sampleCallSOAP();
			break;
		case R.id.bt_date:
			showDatePickerDialog();			
			break;
		case R.id.bt_preview:
			preView();
			
//			dispatchTakePictureIntent();
//			managerImage();
			break;
			
		default:
			break;

		}
	}

	private class MyProcessEvent implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
	}
	
	private void showDatePickerDialog() {
		// TODO Auto-generated method stub

		OnDateSetListener callback = new OnDateSetListener() {
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// can nhat textview
				dates.setText((dayOfMonth) + "/" + (monthOfYear + 1) + "/"
						+ year);
			}
		};
		String s = dates.getText() + "";
		String strArrtmp[] = s.split("/");
		int ngay = Integer.parseInt(strArrtmp[0]);
		int thang = Integer.parseInt(strArrtmp[1]) - 1;
		int nam = Integer.parseInt(strArrtmp[2]);
		DatePickerDialog pic = new DatePickerDialog(MainActivity.this, callback, nam, thang, ngay);
		pic.setTitle("Chọn ngày hoàn thành");
		pic.show();
	}

	private void insertTree() {

		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
		Date date = new Date();

		lo = (Spinner) findViewById(R.id.spinner1);
//		cay = (EditText) findViewById(R.id.e_cay);
		String tinhtrang = getValueTinh_trang();
		String kthuoc_ho = getKthuoc_ho();
		String co_dinh = getCo_dinh();
		String bong_che = getBong_che();
		String nowDate = dateFormat.format(date);
		dates = (EditText) findViewById(R.id.e_date);
		chCao = (EditText) findViewById(R.id.e_cao);
		chVi = (EditText) findViewById(R.id.e_cv);
		String la = getLa();
		String tia_canh = getTia_canh();
		String lam_co = getLam_co();
		String sau_benh = getSau_benh();
		String do_am = getDo_am();
		time_bon = (EditText) findViewById(R.id.e_bon);
		luong_bon = (EditText) findViewById(R.id.e_lphan);
		time_phun = (EditText) findViewById(R.id.e_phun);
		luong_phun = (EditText) findViewById(R.id.e_lthuoc);
		sluong_cay = (EditText) findViewById(R.id.e_trencay);
		sluong_luong = (EditText) findViewById(R.id.e_trenluong);
		String dgia_chung = getDgia_chung();
		vd_khac = (EditText) findViewById(R.id.e_vde);
		String vtri = getVtri();

		int j = lo.getSelectedItemPosition();

		Tree tree = new Tree();
		tree.setLo(getLo(j-1));
		tree.setCay(cay.getText().toString());
		tree.setNgay(nowDate.toString());
		tree.setNgayNhap(dates.getText().toString());
		tree.setTtrang(tinhtrang);
		tree.setKthuoc(kthuoc_ho);
		tree.setCdinh(co_dinh);
		tree.setBche(bong_che);
		tree.setChCao(Double.parseDouble(chCao.getText().toString()));
		tree.setCvi(Double.parseDouble(chVi.getText().toString()));
		tree.setLa(la);
		tree.setTcanh(tia_canh);
		tree.setLco(lam_co);
		tree.setSbenh(sau_benh);
		tree.setDoam(do_am);
		tree.setTimebon(Double.parseDouble(time_bon.getText().toString()));
		tree.setLuongbon(Double.parseDouble(luong_bon.getText().toString()));
		tree.setTimephun(Double.parseDouble(time_phun.getText().toString()));
		tree.setLuongphun(Double.parseDouble(luong_phun.getText().toString()));
		tree.setSlcay(Double.parseDouble(sluong_cay.getText().toString()));
		tree.setSlluong(Double.parseDouble(sluong_luong.getText().toString()));
		tree.setDgia(dgia_chung);
		tree.setVdkhac(vd_khac.getText().toString());
		tree.setVtri(vtri);

		mydb.insertTree(tree);
	}

	public String getLo(int i){
		return Integer.toString(arrParcel.get(i-1).getParcelID());
	}
	public String getValueTinh_trang() {

		int checkedId = rdbGrTinh_trang.getCheckedRadioButtonId();
		if (checkedId == -1) {
			return "";
		}
		RadioButton checkedButton = (RadioButton) findViewById(checkedId);
		return checkedButton.getText().toString();
	}

	public String getKthuoc_ho() {

		int checkedId = rdbGrKthuoc_ho.getCheckedRadioButtonId();
		if (checkedId == -1) {
			return "";
		}
		RadioButton checkedButton = (RadioButton) findViewById(checkedId);
		return checkedButton.getText().toString();
	}

	public String getCo_dinh() {

		int checkedId = rdbGrCo_dinh.getCheckedRadioButtonId();
		if (checkedId == -1) {
			return "";
		}
		RadioButton checkedButton = (RadioButton) findViewById(checkedId);
		return checkedButton.getText().toString();
	}

	public String getBong_che() {

		int checkedId = rdbGrBong_che.getCheckedRadioButtonId();
		if (checkedId == -1) {
			return "";
		}
		RadioButton checkedButton = (RadioButton) findViewById(checkedId);
		return checkedButton.getText().toString();
	}

	public String getLa() {

		String a, b, c, d, e, f, g, h;

		if (chk_bt.isChecked())
			a = chk_bt.getText().toString();
		else
			a = "-";

		if (chk_chm.isChecked())
			b = chk_chm.getText().toString();
		else
			b = "-";

		if (chk_vla.isChecked())
			c = chk_vla.getText().toString();
		else
			c = "-";

		if (chk_bla.isChecked())
			d = chk_bla.getText().toString();
		else
			d = "-";

		if (chk_dlo.isChecked())
			e = chk_dlo.getText().toString();
		else
			e = "-";

		if (chk_xla.isChecked())
			f = chk_xla.getText().toString();
		else
			f = "-";

		if (chk_bthung.isChecked())
			g = chk_bthung.getText().toString();
		else
			g = "-";

		if (chk_khac.isChecked())
			h = chk_khac.getText().toString();
		else
			h = "-";

		return (a + "," + b + "," + c + "," + d + "," + e + "," + f + "," + g
				+ "," + h).toString();
	}

	public String getTia_canh() {

		int checkedId = rdbGrTia_canh.getCheckedRadioButtonId();
		if (checkedId == -1) {
			return "";
		}
		RadioButton checkedButton = (RadioButton) findViewById(checkedId);
		return checkedButton.getText().toString();
	}

	public String getLam_co() {

		int checkedId = rdbGrLam_co.getCheckedRadioButtonId();
		if (checkedId == -1) {
			return "";
		}
		RadioButton checkedButton = (RadioButton) findViewById(checkedId);
		return checkedButton.getText().toString();
	}

	public String getSau_benh() {

		String a, b, c, d, e, f;

		if (chk_tThu.isChecked())
			b = chk_tThu.getText().toString();
		else
			b = "-";

		if (chk_phy.isChecked())
			a = chk_phy.getText().toString();
		else
			a = "-";

		if (chk_rSap.isChecked())
			c = chk_rSap.getText().toString();
		else
			c = "-";

		if (chk_rVang.isChecked())
			d = chk_rVang.getText().toString();
		else
			d = "-";

		if (chk_chau.isChecked())
			e = chk_chau.getText().toString();
		else
			e = "-";

		if (chk_skhac.isChecked())
			f = chk_skhac.getText().toString();
		else
			f = "-";
		return (a + "," + b + "," + c + "," + d + "," + e + "," + f).toString();

	}

	public String getDo_am() {

		int checkedId = rdbGrDo_am.getCheckedRadioButtonId();
		if (checkedId == -1) {
			return "";
		}
		RadioButton checkedButton = (RadioButton) findViewById(checkedId);
		return checkedButton.getText().toString();
	}

	public String getDgia_chung() {

		int checkedId = rdbGrDgia_chung.getCheckedRadioButtonId();
		if (checkedId == -1) {
			return "";
		}
		RadioButton checkedButton = (RadioButton) findViewById(checkedId);
		return checkedButton.getText().toString();
	}

	public String getVtri() {

		GPSTracker tracker = new GPSTracker(this);
		if (tracker.canGetLocation() == false) {

			return " ";
		} else {
			return String.valueOf(tracker.getLatitude()) + ","
					+ String.valueOf(tracker.getLongitude());

		}

	}

	private void sampleCallSOAP() {
//		DBHelper mydb = new DBHelper(this);
//		String value = "user ; lo; cay; ngay; ngayNhap; ttrang; kthuoc; cdinh; bche; "
//						+"chCao; cvi; la; tcanh; lco; sbenh;  doam; timebon; luongbon;"
//						+ "timephun; luongphun; slcay; slluong; dgia; vdkhac; vtri";
//		String value1 = mydb.getData();

//		mydb.close();

		// String value = user.getText().toString();
		// if (TextUtils.isEmpty(value)) {
		 String value = "admin";
		// }
		PropertyInfo proInfo = new PropertyInfo();
		proInfo.setName("UserName");
		proInfo.setValue(value);
		proInfo.setType(String.class);
		
//		proInfo.setName("giaTri");
//		proInfo.setValue(value);
//		proInfo.setType(String.class);
//		
		HttpHandler httpHandler = new HttpHandler(SoapHelper.METHOD_GetUserParcels, proInfo) {

			@Override
			public void onResponse(int errorCode, String result) {
				// hide progress dialog khi API tra ve (bat buoc phai goi hide,
				// neu co goi show)
				arrUser = new ArrayList<UserParcel>();
				Alerts.hideLoadingDialog();
				Logger.error("[onResponse] errorCode:" + errorCode);
				// Logger.error("[onResponse] result:" + result);
//			BaseApplication.makeToastMsg("[onResponse] result:" + result);
				// truoc khi su dung string ket qua tra ve phai check null va
				// empty (nen dung TextUtils.isEmpty)
				// truoc khi parse thi nen kiem tra data co hop lệ hay khong
				if (TextUtils.isEmpty(result) || !result.contains(";")) {
					Alerts.showButtonDialog(MainActivity.this,
							"Get user information failed. Please try again.",
							null);
					return;
				}
				String[] rows = result.split(";");
				// thieu check null truoc khi su dung, neu khong app se bi crash
				// do nullPointerException
				// should add code
				if (rows == null)
					return;
				String value = user.getText().toString();
				for (int i = 0; i < rows.length; i++) {
					String[] cols = rows[i].split(":");
					UserParcel up = new UserParcel();
					up.setParcelID(Integer.parseInt(cols[0]));
					up.setParcelName(cols[1].toString());
					up.setUserName(value);
					userdb.comPare1(up);
					arrUser.add(up);
				}
				userdb.comPare2(arrUser,value);
			}
		};
		// ktra network truoc khi goi API
		if (Utils.isEnableNetwork(this, true)) {
			// show progress dialog
			Alerts.showLoadingDialog(this, null, null);
			httpHandler.execute();
		}
	}

	public void CallSOAP() {
		DBHelper mydb = new DBHelper(this);

		String value1 = mydb.getData();

		mydb.close();
		
		
		/*
		 * PropertyInfo proInfo1 = new PropertyInfo();
		 * proInfo1.setName("UserName"); proInfo1.setValue(value1);
		 * proInfo1.setType(String.class);
		 * 
		 * HttpHandler httpHandler1 = new HttpHandler(SoapHelper.METHOD_NAME,
		 * proInfo1){
		 * 
		 * @Override public void onResponse(int errorCode, String result){
		 * Alerts.hideLoadingDialog(); Logger.error("[onResponse] errorCode:" +
		 * errorCode);
		 * 
		 * }
		 * 
		 * 
		 * };
		 * 
		 * if (Utils.isEnableNetwork(this, true)) { // show progress dialog
		 * Alerts.showLoadingDialog(this, null, null); httpHandler1.execute(); }
		 */
	}
	
	private void preView() {
		// TODO Auto-generated method stub
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
		Date date = new Date();
		
		lo = (Spinner) findViewById(R.id.spinner1);
		cay = (EditText) findViewById(R.id.e_cay);
		String tinhtrang = getValueTinh_trang();
		String kthuoc_ho = getKthuoc_ho();
		String co_dinh = getCo_dinh();
		String bong_che = getBong_che();
		String nowDate = dateFormat.format(date);
		dates = (EditText) findViewById(R.id.e_date);
		chCao = (EditText) findViewById(R.id.e_cao);
		chVi = (EditText) findViewById(R.id.e_cv);
		String la = getLa();
		String tia_canh = getTia_canh();
		String lam_co = getLam_co();
		String sau_benh = getSau_benh();
		String do_am = getDo_am();
		time_bon = (EditText) findViewById(R.id.e_bon);
		luong_bon = (EditText) findViewById(R.id.e_lphan);
		time_phun = (EditText) findViewById(R.id.e_phun);
		luong_phun = (EditText) findViewById(R.id.e_lthuoc);
		sluong_cay = (EditText) findViewById(R.id.e_trencay);
		sluong_luong = (EditText) findViewById(R.id.e_trenluong);
		String dgia_chung = getDgia_chung();
		vd_khac = (EditText) findViewById(R.id.e_vde);
		String vtri = getVtri();
		
		int j = lo.getSelectedItemPosition();
		
		Tree tree = new Tree();
		tree.setLo(getLo(j-1));
		tree.setCay(cay.getText().toString());
		tree.setNgay(nowDate.toString());
		tree.setNgayNhap(dates.getText().toString());
		tree.setTtrang(tinhtrang);
		tree.setKthuoc(kthuoc_ho);
		tree.setCdinh(co_dinh);
		tree.setBche(bong_che);
		tree.setChCao(Double.parseDouble(chCao.getText().toString()));
		tree.setCvi(Double.parseDouble(chVi.getText().toString()));
		tree.setLa(la);
		tree.setTcanh(tia_canh);
		tree.setLco(lam_co);
		tree.setSbenh(sau_benh);
		tree.setDoam(do_am);
		tree.setTimebon(Double.parseDouble(time_bon.getText().toString()));
		tree.setLuongbon(Double.parseDouble(luong_bon.getText().toString()));
		tree.setTimephun(Double.parseDouble(time_phun.getText().toString()));
		tree.setLuongphun(Double.parseDouble(luong_phun.getText().toString()));
		tree.setSlcay(Double.parseDouble(sluong_cay.getText().toString()));
		tree.setSlluong(Double.parseDouble(sluong_luong.getText().toString()));
		tree.setDgia(dgia_chung);
		tree.setVdkhac(vd_khac.getText().toString());
		tree.setVtri(vtri);
			
		Intent intent = new Intent(this, displayTree.class);
		intent.putExtra(PAR, tree);
		startActivity(intent);
	}
	
	
	
	public void managerImage(){
		Bundle data = new Bundle();
		data.putString("user", user.getText().toString());
		Intent intent = new Intent(this, ManagerPicture.class);
		intent.putExtras(data);
		startActivity(intent);
	}
	
	
}



